﻿using AutoMapper;
using ETask.Api.Mappers;
using ETask.Api.Models;
using ETask.Api.Repositories;
using System.Reflection;

namespace ETask.Api.Data
{
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 注册所有仓储和服务
        /// </summary>
        public static IServiceCollection AddRepositoriesAndServices(this IServiceCollection services)
        {
            // 注册通用仓储
            services.AddScoped(typeof(IRepository<>), typeof(Repository<>));

            // 注册所有自定义仓储和服务
            RegisterRepositories(services);
            RegisterServices(services);

            return services;
        }

        /// <summary>
        /// 自动注册所有仓储（实现了IXXXRepository并继承RepositoryBase的类）
        /// </summary>
        private static void RegisterRepositories(IServiceCollection services)
        {
            var assembly = Assembly.GetExecutingAssembly();

            // 获取所有仓储接口
            var repositoryInterfaces = assembly.GetTypes()
                .Where(t => t.IsInterface && t.Name.EndsWith("Repository"))
                .ToList();

            foreach (var interfaceType in repositoryInterfaces)
            {
                // 查找对应的实现类
                var implementationType = assembly.GetTypes()
                    .FirstOrDefault(t => t.IsClass && !t.IsAbstract &&
                                        interfaceType.IsAssignableFrom(t));

                if (implementationType != null)
                {
                    services.AddScoped(interfaceType, implementationType);
                }
            }
        }

        /// <summary>
        /// 自动注册所有服务（实现了IXXXService的类）
        /// </summary>
        private static void RegisterServices(IServiceCollection services)
        {
            var assembly = Assembly.GetExecutingAssembly();

            // 获取所有服务接口
            var serviceInterfaces = assembly.GetTypes()
                .Where(t => t.IsInterface && t.Name.EndsWith("Service"))
                .ToList();

            foreach (var interfaceType in serviceInterfaces)
            {
                // 查找对应的实现类
                var implementationType = assembly.GetTypes()
                    .FirstOrDefault(t => t.IsClass && !t.IsAbstract &&
                                        interfaceType.IsAssignableFrom(t));

                if (implementationType != null)
                {
                    services.AddScoped(interfaceType, implementationType);
                }
            }
        }
    }
}
